#include <Arduino.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>
// 2022.6.14——ESP01S  知心天气 调试完成
/* ////////////////////////////////////////////////
    实验板：ESP01S
    版本：V0.1
    更改内容:
        V0.1：知心天气 调试完成
            1.修复了json解析有一部分不能使用的问题
            2.私钥：SeiP2ViJVtkngR1s5
            3.接口地址//https://api.seniverse.com/   v3/weather/now.json?
                              key=your_api_key
                              &location=beijing
                              &language=zh-Hans
                              &unit=c
*/
////////////////////////////////////////////////

// WiFi settings
const char *ssid = "123456";
const char *password = "776654321";
const char *host = "api.seniverse.com"; // API server

WiFiClient client;
int httpPort = 80;

String key = "SeiP2ViJVtkngR1s5";
String location = "luoyang";
String language = "zh-Hans";

String jsonAnswer;
int jsonIndex;

void client_respon()
{
  String answer;
  if (!client.connect(host, httpPort)) // TCP连接是否成功，不成功再重试
  {
    Serial.println("connection failed");
    return;
  }

  String url = "/v3/weather/daily.json?key=" + key + "&location=" + location + "&language=" + language + "&unit=c&start=0&days=3";
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                "Host: " + host + "\r\n" +
                "Connection: close\r\n\r\n");
  delay(100);
  //将每行的返回值加入到answer
  while (client.available())
  {
    String line = client.readStringUntil('\r'); // terminator: 终止字符。用于设置终止函数执行的字符信息。设备在读取数据时一旦读取到此终止字符，将会结束函数执行。允许使用char类型。
    answer += line;
  }
  client.stop();                            //关闭连接

  for (int i = 0; i < answer.length(); i++) //如果开头为{目录就为i
  {
    if (answer[i] == '{')
    {
      jsonIndex = i;
      break;
    }
  }

  // Get JSON data
  jsonAnswer = answer.substring(jsonIndex);
}

void start_weather_json()
{
}

void setup()
{
  Serial.begin(115200);
  delay(10);
  // WIFI开始连接
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) //等待wifi连接成功
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop()
{
  client_respon();

  // String input;
  DynamicJsonDocument doc(1536);
  DeserializationError error = deserializeJson(doc, jsonAnswer);

  // if (error)
  // {
  //   Serial.print(F("deserializeJson() failed: "));
  //   Serial.println(error.f_str());
  //   return;
  // }

  JsonObject results_0 = doc["results"][0];

  JsonObject results_0_location = results_0["location"];
  const char *results_0_location_id = results_0_location["id"];                           // "WQPUYY7S4GV2"
  const char *results_0_location_name = results_0_location["name"];                       // "洛阳"
  const char *results_0_location_country = results_0_location["country"];                 // "CN"
  const char *results_0_location_path = results_0_location["path"];                       // "洛阳,洛阳,河南,中国"
  const char *results_0_location_timezone = results_0_location["timezone"];               // "Asia/Shanghai"
  const char *results_0_location_timezone_offset = results_0_location["timezone_offset"]; // "+08:00"

  //!关键点，把daily下的每一个{}视为数组调用，现在调用的是今天的数据
  JsonObject results_0_daily_item = results_0["daily"][0];
  const char *results_0_daily_item_date = results_0_daily_item["date"];                     // "2022-06-14", "2022-06-15", ...
  const char *results_0_daily_item_text_day = results_0_daily_item["text_day"];             // "晴", "晴", "晴"
  const char *results_0_daily_item_code_day = results_0_daily_item["code_day"];             // "0", "0", "0"
  const char *results_0_daily_item_text_night = results_0_daily_item["text_night"];         // "晴", "晴", "晴"
  const char *results_0_daily_item_code_night = results_0_daily_item["code_night"];         // "1", "1", "1"
  const char *results_0_daily_item_high = results_0_daily_item["high"];                     // "35", "36", "37"
  const char *results_0_daily_item_low = results_0_daily_item["low"];                       // "20", "21", "24"
  const char *results_0_daily_item_rainfall = results_0_daily_item["rainfall"];             // "0.00", "0.00", "0.00"
  const char *results_0_daily_item_precip = results_0_daily_item["precip"];                 // "0.00", "0.00", "0.00"
  const char *results_0_daily_item_wind_direction = results_0_daily_item["wind_direction"]; // "西", "东北", ...
  const char *results_0_daily_item_wind_direction_degree = results_0_daily_item["wind_direction_degree"];
  const char *results_0_daily_item_wind_speed = results_0_daily_item["wind_speed"]; // "23.4", "8.4", ...
  const char *results_0_daily_item_wind_scale = results_0_daily_item["wind_scale"]; // "4", "2", "3"
  const char *results_0_daily_item_humidity = results_0_daily_item["humidity"];     // "47", "38", "42"

  const char *results_0_last_update = results_0["last_update"]; // "2022-06-14T08:00:00+08:00"

  Serial.println(results_0_location_name);
  Serial.println(results_0_daily_item_date);
  Serial.println(results_0_daily_item_high);
  delay(2000);
}
